<template>
  <div class="ckeditor-box" :style="{'width':width,'min-height':height}">
    <div ref="editorDom" v-html="compValue"></div>
  </div>
</template>

<script lang="ts" setup>
defineOptions({
  name: "VueEditor"
});

// @ts-ignore
import ClassicEditor from 'vue-ckeditor5-auto/build/ckeditor'
// @ts-ignore
import {ref, watch, onMounted, getCurrentInstance} from 'vue'

const props = defineProps({
  width: {
    type: String, default: 'calc(100% - 10px)'
  },
  height: {
    type: String, default: '450px'
  },
  value: {
    type: String, default: ''
  },
  toolBar: {
    type: Array, default: function () {
      return []
    }
  },
  fontSize: {
    type: Array, default: function () {
      return []
    }
  }
});
let myEditor: any = null;

const compValue = ref("");

const editorConfig = ref<any>({
  fontSize: {
    options: [12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 44]
  },
  fontFamily: {
    options: [
      '微软雅黑',
      '等线',
      '新宋体',
      '宋体',
      '仿宋',
      '黑体',
      '楷体',
      '华文彩云'
    ]
  }
});
//监听变化
watch(() => props.value, () => {
  if (props.value != compValue.value) {
    myEditor.setData(props.value)
  }
})


// @ts-ignore
let {proxy} = getCurrentInstance()

const editorDom = ref<any>(null);

onMounted(() => {
  initEditor();
})
const emit = defineEmits(['update:value'])

const initEditor = () => {
  if (props.toolBar?.length > 0) {
    editorConfig.value.toolbar.items = props.toolBar;
  }

  if (props.fontSize?.length > 0) {
    editorConfig.value.fontSize.options = props.fontSize;
  }
  ClassicEditor.create(editorDom.value, editorConfig.value)
      .then((editor: any) => {
        editor.setData(props.value)
        editor.plugins.get('FileRepository').createUploadAdapter = (loader: any) => {
          return new UpdateFile(loader)
        }
        editor.model.document.on('change:data', function () {
          compValue.value = editor.getData();
          emit('update:value', compValue.value);
        })

        myEditor = editor;
      })
      .catch((error: any) => {
        console.error(error)
      })
}


class UpdateFile {
  loader: any;

  constructor(loader: any) {
    // Save Loader instance to update upload progress.
    this.loader = loader
  }

  async upload() {
    const data = new FormData()
    data.append("file", await this.loader.file)
    return new Promise((resolve, reject) => {
      proxy.$http.upload(data).then((data: any) => {
        console.log(data)
        let resData = data;
        resData.default = data.browser
        resolve(resData)
      });
    })
  }
}
</script>

<style lang="less" scoped>
.ckeditor-box {
  padding: 5px;
  height: 100%;
  position: relative;
}

.ckeditor-box :deep(.ck-editor) {
  width: calc(100%);
  height: 100%;
}

.ckeditor-box :deep( .ck-editor__main ) {
  width: 100%;
  height: calc(100% - 40px);
}

.ckeditor-box :deep(.ck-content) {
  min-height: v-bind(height);
}
</style>
